<?php

        const GENTHUMB_JPEG_QUALITY = 90;
        const IMAGES_CACHE_URL = 'cache/genimages';
        const THUMBS_CACHE_URL = 'cache/genthumbs';
        const FONTS_RELATIVE_PATH = 'application/views/fonts';
        const OLD_GD_ALPHA_FIX = false;

class Jhg_TwigExtention_Image extends Twig_Extension {

    private $genthumbTypes = array(
        0 => array('w' => 258, 'h' => 165, 'thumb_type' => 'shrink_to_fit_and_crop', 'can_enlarge' => false, 'bgc' => array(255, 255, 255)),
        1 => array('w' => 100, 'h' => 100, 'thumb_type' => 'shrink_to_fit_and_crop', 'can_enlarge' => false, 'bgc' => array(255, 255, 255))
    );

    public function getName() {
        return 'app_image';
    }

    public function getFilters() {
        return array(
            'genimage' => new Twig_Filter_Method($this, 'genimageFilter'),
            'genthumb' => new Twig_Filter_Method($this, 'genthumbFilter'),
        );
    }

    public function genimageFilter($text, $type) {
        list($imagePath, $imageUrl, $fontsPath) = $this->textToPaths($text, $type);

        if (file_exists($imagePath)) {
            return $imageUrl;
        }

        switch ($type) {
            case 0: //title red
                $sx = 765;
                $sy = 42;
                $scale = 4;
                
                // $text = mb_strtoupper($text, 'utf-8');

                $im_clear = imagecreatefrompng($fontsPath . 'titlebg.png');
                $im_scaled = $this->transparent_image_create($sx, $sy);

                $font = $fontsPath . 'monume_8.ttf';
                imagettftext($im_clear, 14 * $scale, 0, 16 * $scale, 28 * $scale, imagecolorallocate($im_clear, 213, 24, 30), $font, $text);

                $this->transparent_image_resample($im_clear, $im_scaled);
                imagepng($im_scaled, $imagePath);
                break;
            case 1: //title black
                $sx = 765;
                $sy = 42;
                $scale = 4;

                $im_clear = imagecreatefrompng($fontsPath . 'titlebg2.png');
                $im_scaled = $this->transparent_image_create($sx, $sy);

                $font = $fontsPath . 'monume_8.ttf';
                imagettftext($im_clear, 14 * $scale, 0, 16 * $scale, 28 * $scale, imagecolorallocate($im_clear, 0, 0, 0), $font, $text);

                $this->transparent_image_resample($im_clear, $im_scaled);
                imagepng($im_scaled, $imagePath);
                break;
        }

        return $imageUrl;
    }

    public function genthumbFilter($originalUrl, $thumbType) {
        list($originalPath, $originalType, $thumbUrl, $thumbPath) = $this->urlToPaths($originalUrl, $thumbType);

        if (file_exists($thumbPath)) {
            return $thumbUrl;
        }

        if ($originalType == 'jpg' || $originalType == 'jpeg')
            $sim = imagecreatefromjpeg($originalPath);
        if ($originalType == 'gif')
            $sim = imagecreatefromgif($originalPath);
        if ($originalType == 'png')
            $sim = imagecreatefrompng($originalPath);

        $sw = imagesx($sim);
        $sh = imagesy($sim);

        $GENTHUMB_TYPES = $this->genthumbTypes;

        $w = $GENTHUMB_TYPES[$thumbType]['w'];
        $h = $GENTHUMB_TYPES[$thumbType]['h'];

        if ($GENTHUMB_TYPES[$thumbType]['thumb_type'] == 'shrink_to_fit_and_draw' ||
                $GENTHUMB_TYPES[$thumbType]['thumb_type'] == 'shrink_to_fit_and_crop') {

            if (!$GENTHUMB_TYPES[$thumbType]['can_enlarge'] && $sw <= $w && $sh <= $h) {
                $h = $sh;
                $w = $sw;
            }

            $im = imagecreatetruecolor($w, $h);

            if ($GENTHUMB_TYPES[$thumbType]['thumb_type'] == 'shrink_to_fit_and_draw')
                $scale = $sh / $h > $sw / $w ? $sh / $h : $sw / $w;
            else
                $scale = $sh / $h < $sw / $w ? $sh / $h : $sw / $w;

            $tw = $w;
            $th = $h;
            $w = $sw / $scale;
            $h = $sh / $scale;
            $dx = ($tw - $w) / 2;
            $dy = ($th - $h) / 2;

            if (isset($GENTHUMB_TYPES[$thumbType]['bgc'])) {
                $bgc = imagecolorallocate($im, $GENTHUMB_TYPES[$thumbType]['bgc'][0], $GENTHUMB_TYPES[$thumbType]['bgc'][1], $GENTHUMB_TYPES[$thumbType]['bgc'][2]);
                imagefilledrectangle($im, 0, 0, $tw, $th, $bgc);
            } else {
                if ($dx > 0) {
                    imagecopyresampled($im, $sim, 0, 0, 0, 0, $dx + 1, $th, 1, $sh);
                    imagecopyresampled($im, $sim, $tw - $dx - 1, 0, $sw - 1, 0, $dx + 2, $th, 1, $sh);
                }
                if ($dy > 0) {
                    imagecopyresampled($im, $sim, 0, 0, 0, 0, $tw, $dy + 1, $sw, 1);
                    imagecopyresampled($im, $sim, 0, $th - $dy - 1, 0, $sh - 1, $tw, $dy + 2, $sw, 1);
                }
            }

            imagecopyresampled($im, $sim, $dx, $dy, 0, 0, $w, $h, $sw, $sh);
        } else {
            $scale = $sh / $h < $sw / $w ? $sh / $h : $sw / $w;
            $dx = ($sw - $w * $scale) / 2;
            $dy = ($sh - $h * $scale) / 2;


            $im = imagecreatetruecolor($w, $h);
            $bgc = imagecolorallocate($im, $GENTHUMB_TYPES[$thumbType]['bgc'][0], $GENTHUMB_TYPES[$thumbType]['bgc'][1], $GENTHUMB_TYPES[$thumbType]['bgc'][2]);
            imagefilledrectangle($im, 0, 0, $w, $h, $bgc);

            imagecopyresampled($im, $sim, 0, 0, $dx, $dy, $w, $h, $sw - 2 * $dx, $sh - 2 * $dy);
        }

        imagejpeg($im, $thumbPath, GENTHUMB_JPEG_QUALITY);

        return $thumbUrl;
    }

    private function urlToPaths($url, $postfix = '') {
        $basePath = realpath(APPLICATION_PATH . DIRECTORY_SEPARATOR . '..');
        $cachePath = $basePath . DIRECTORY_SEPARATOR . THUMBS_CACHE_URL;

        $originalPath = parse_url($url, PHP_URL_PATH);
        $originalPath = trim($originalPath, '/');
        $originalPath = $basePath . DIRECTORY_SEPARATOR . $originalPath;

        $originalType = pathinfo($originalPath, PATHINFO_EXTENSION);
        $originalType = strtolower($originalType);

        $url = strtolower($url);
        $url = md5($url) . '_' . $postfix . '.jpg';
        $thumbsUrl = '/' . THUMBS_CACHE_URL . '/' . $url;
        $thumbsPath = $cachePath . DIRECTORY_SEPARATOR . $url;

        return array($originalPath, $originalType, $thumbsUrl, $thumbsPath);
    }

    private function textToPaths($text, $postfix = '') {
        $basePath = realpath(APPLICATION_PATH . DIRECTORY_SEPARATOR . '..');
        $cachePath = $basePath . DIRECTORY_SEPARATOR . IMAGES_CACHE_URL;

        $text = strtolower($text);
        $url = md5($text) . '_' . $postfix . '.png';

        $imagePath = $cachePath . DIRECTORY_SEPARATOR . $url;
        $imageUrl = '/' . IMAGES_CACHE_URL . '/' . $url;
        $fontsPath = $basePath . DIRECTORY_SEPARATOR . FONTS_RELATIVE_PATH . DIRECTORY_SEPARATOR;
        return array($imagePath, $imageUrl, $fontsPath);
    }

    private function transparent_image_create($size_x, $size_y) {
        $im = imagecreatetruecolor($size_x, $size_y);
        imagesavealpha($im, true);
        imagealphablending($im, false);
        imagefilledrectangle($im, 0, 0, $size_x, $size_y, imagecolorallocatealpha($im, 0, 0, 0, 127));
        imagealphablending($im, !OLD_GD_ALPHA_FIX);
        return $im;
    }

    private function transparent_image_resample(&$im_from, &$im_to) {
        imagealphablending($im_to, false);
        imagecopyresampled($im_to, $im_from, 0, 0, 0, 0, imagesx($im_to), imagesy($im_to), imagesx($im_from), imagesy($im_from));
        imagealphablending($im_to, true);
    }

}
